package star.servlet_2;

import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.FileInputStream;
import java.io.IOException;


//http响应：响应和状态码
public class Response_6 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取下载文件的路径，名称
        String path = "E:\\study\\computer\\Project\\Maven\\STAR_maven\\Servlet_2\\target\\classes\\1.png";//this.getServletContext().getRealPath("/1.png");
        System.out.println("下载文件的路径" + path);
        //获取文件名字
        String name = path.substring(path.lastIndexOf("\\")+1);
        //2.设置想办法让浏览器支持我们下载需要的东西
        resp.setHeader("Content-disposition", "attachment; " +  "filename="+name);
        //3.获取下载文件的输入流
        FileInputStream in = new FileInputStream(path);
        //4.创建缓冲区
        int len = 0 ;
        byte[] buffer = new  byte[1024];

        //5.获取Outputstream对象
        ServletOutputStream out = resp.getOutputStream();
        //6.将FileoutputStream流写入到buffer缓冲区,使用OutputStream将缓冲区中的数据输出到客户端！
        while((len = in.read(buffer))!=-1)
        {
            out.write(buffer,0,len);
        }

        //关闭
        in.close();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }



}
